//index.js
//获取应用实例
const app = getApp();
let col1H = 0;
let col2H = 0;

Page({
  data: {
    col1:[],
    col2:[],
    scrollH:0,
    imgWidth:0,
    images:[],
    loadingCount:0,
  },
  onLoad: function () {
    wx.getSystemInfo({
      success:(res)=>{
        //console.log(res)
        let wx = res.windowWidth;
        let wh = res.windowHeight;
        let imgWidth = wx * 0.48;
        let scrollH = wh;
        this.setData({
          scrollH: scrollH,
          imgWidth:imgWidth
        }); 
        this.loadimage();
      }
    })
  },
  loadimage(){
    let images =  [
      { pic: '../images/1.jpeg', height: 0 },
      { pic: '../images/2.jpeg', height: 0 },
      { pic: '../images/3.jpeg', height: 0 },
      { pic: '../images/4.jpeg', height: 0 },
      { pic: '../images/5.jpeg', height: 0 },
      { pic: '../images/6.jpeg', height: 0 },
      { pic: '../images/7.jpeg', height: 0 },
      { pic: '../images/8.jpeg', height: 0 },
      { pic: '../images/9.jpeg', height: 0 },
      { pic: '../images/10.jpeg', height: 0 },
      { pic: '../images/11.jpeg', height: 0 },
      { pic: '../images/12.jpeg', height: 0 },
      { pic: '../images/13.png', height: 0 },
      { pic: '../images/14.jpeg', height: 0 },
    ];

    let baseId = 'img-'+ (+new Date());
    images.forEach((val,index) => {
      val.id = baseId + '-' + index;
    });

    this.setData({
      images: images,
      loadingCount: images.length
    })
  },
  onImageLoad(e){
    //console.log(e);
    let imageId = e.currentTarget.id;
    let oImgH = e.detail.height;
    let oImgW = e.detail.width;
    let imgWidth = this.data.imgWidth;
    let scale = imgWidth / oImgW;
    let imgHeight = oImgH * scale;
    let images = this.data.images;
    let imageObj = null;

    for (var i = 0; i < images.length;i++){
      var img = images[i];
      if (img.id === imageId){
        imageObj = img;
        break;
      }
    }
    imageObj.height = imgHeight;

    let loadingCount = this.data.loadingCount - 1;
    let col1 = this.data.col1;
    let col2 = this.data.col2;

    if(col1H <= col2H){
      col1H += imgHeight;
      col1.push(imageObj);
    }else{
      col2H += imgHeight;
      col2.push(imageObj);
    }

    let data = {
      loadingCount: loadingCount,
      col1: col1,
      col2: col2
    }

    if (loadingCount == 0){
      data.images = [];
    }

    this.setData(data)
  }
})
